import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/service/user.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:reactive_forms/reactive_forms.dart';

class ResetPasswordByEmailTab extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Log.debug('build ResetPasswordByEmailTab');
    final UserServiceProvider _userservice = new UserServiceProvider();

    final form = FormGroup({
      'username': FormControl<String>(validators: [Validators.required]),
    });

    void _resetPasswordByEmail(String username) async {
      try {
        EasyLoading.show();
        var response = await _userservice.resetPasswordByEmail(username);
        if (response.statusCode == 200) {
          Get.snackbar('Message'.tr,
              'Please check password reset link in your email.'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
        } else {
          Get.snackbar('Message'.tr, 'Failed to reset password with email.'.tr,
              backgroundColor: Theme.of(context).primaryColor,
              colorText: Theme.of(context).primaryColorLight,
              snackPosition: SnackPosition.BOTTOM);
        }
      } catch (e) {
      } finally {
        EasyLoading.dismiss();
      }
    }

    return Padding(
      padding: const EdgeInsets.fromLTRB(50, 36, 50, 18),
      child: ReactiveForm(
        formGroup: form,
        child: Column(
          children: <Widget>[
            ReactiveTextField(
              formControlName: 'username',
              textInputAction: TextInputAction.next,
              style: Theme.of(context).textTheme.titleSmall,
              decoration: InputDecoration(
                  alignLabelWithHint: true,
                  labelText: 'User Name'.tr,
                  helperText: 'Instructions will be sent to your email.'.tr),
            ),
            SizedBox(
              height: 12,
            ),
            ReactiveFormConsumer(
              builder: (context, form, child) {
                return ElevatedButton(
                    child: Text('Submit'.tr),
                    onPressed: () {
                      if (form.valid) {
                        _resetPasswordByEmail(form.control('username').value);
                      }
                    });
              },
            ),
          ],
        ),
      ),
    );
  }
}
